//
//  ZDDComposeViewController.swift
//  小蜗牛_新浪微博
//
//  Created by 周冬冬 on 16/7/3.
//  Copyright © 2016年 我的mac. All rights reserved.
//

import UIKit

class ZDDComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    private func setupUI(){
    
    view.backgroundColor = UIColor.whiteColor()
    setupNav()
        //添加控件
        view.addSubview(composeTextView)
        view.addSubview(composeToolbar)
        composeTextView.addSubview(pictureView)
        
        
        //添加约束
       composeTextView.snp_makeConstraints { (make) -> Void in
        make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        //底部toolbar
        composeToolbar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        //配图
        pictureView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(composeTextView).offset(StautsMargin)
            make.top.equalTo(composeTextView.snp_top).offset(100)
            make.size.equalTo(CGSize(width: kScreenW - StautsMargin*2, height: kScreenW - StautsMargin*2))
            
        }
        pictureView.composePictureViewClosure = {[weak self]()->() in
        
            self?.selectImage()
        
        
        }
        // 监听composeToolbar 中的按钮店家
        composeToolbar.closure = {[weak self] (type: ZDDComposeToolbarType) ->() in
            switch type{
            case .Picture:
                self?.selectImage()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                self?.switchKeyboard()
            case .Add:
                print("+")
                
            }
        }
        //监听按钮的点击
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    func keyboardWillChangeFrame(noti:NSNotification){
    
        let rect = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        
        //更新约束
        composeToolbar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(rect.origin.y - kScreenH)
        }
    UIView.animateWithDuration(0.25, animations: { () -> Void in
        
        self.view.layoutIfNeeded()
        
        })
    
    
    }
    deinit{
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    
    }
    private func setupNav(){
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        navigationItem.titleView = titleView
    navigationItem.rightBarButtonItem?.enabled = false
    
    }
    
    @objc private func cancel(){
        composeTextView.resignFirstResponder()
        dismissViewControllerAnimated(false, completion: nil)
    }
    @objc private func send(){
        if pictureView.imageList.count > 0{
        //代表有图
            upload()
            
        }else{
        upDate()
        }
        
    }
    
//    懒加载控件
    private lazy var titleView : UILabel = {
    
        let name = ZDDUserAccountTools.sharedTools.userAccount?.screen_name ?? ""
        let str = "发微博\n\(name)"
        let range = (str as NSString).rangeOfString(name)
        //富文本
        let attr = NSMutableAttributedString(string: str)
        
        //设置富文本
        attr.addAttributes([NSForegroundColorAttributeName:ThemeColor,NSFontAttributeName:UIFont.systemFontOfSize(13)],  range: range)
        let lab = UILabel()
        lab.attributedText = attr
        lab.textAlignment = .Center
        lab.numberOfLines = 0
    //给label设置宽高
        lab.sizeToFit()
        return lab
     
    }()
    //textView 
    private lazy var composeTextView:ZDDComposeTextView = {
    
        let view = ZDDComposeTextView()
        view.font = UIFont.systemFontOfSize(16)
        view.delegate = self
        view.alwaysBounceVertical = true
    view.placeholder = "我感冒了不想上课我感冒了不想上课我感冒了不想上课我感冒了不想上课我感冒了不想上课我感冒了不想上课我感冒了不想上课我感冒了不想上课我感冒了不想上课我感冒了"
        return view
      
    }()
    //底部TOOLbar
    private lazy var composeToolbar:ZDDComposeToolBar = ZDDComposeToolBar()
    //图片
    private lazy var pictureView:ZDDComposePictureView = ZDDComposePictureView()
    //自定义表情键盘
    private lazy var keyboardView:ZDDEmoticonKeyboard = {
    
        let view = ZDDEmoticonKeyboard()
        view.frame = CGRect(x: 0, y: 0, width: kScreenW, height: 216)
    
    return view
    
    }()
}
extension ZDDComposeViewController{

    func upDate(){
    
    ZDDNetworkTools.sharedTools.composeUpdate(composeTextView.text, success: { (response) -> () in
        print("发送成功")
        }) { (error) -> () in
            print("发送失败")
        }
    }

    func upload(){
    
        ZDDNetworkTools.sharedTools.comoposeUpload(composeTextView.text, imageList: pictureView.imageList, success: { (response) -> () in
            print("发送成功")
            }) { (error) -> () in
                print("发送失败")
        }
    
        
    
    }

}
extension ZDDComposeViewController:UITextViewDelegate{

    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    

    func scrollViewDidScroll(scrollView: UIScrollView) {
        composeTextView.resignFirstResponder()
    }



}
//toolbar的点击事件的处理

extension ZDDComposeViewController{

    func selectImage(){
    
        let picker = UIImagePickerController()
        //设置代理
        picker.delegate = self
        presentViewController(picker, animated: true, completion: nil)
    
    }
    func switchKeyboard(){
    
        if composeTextView.inputView == nil{
        
            composeTextView.inputView = keyboardView
            
            composeToolbar.isEmoticon = true
            
        
        }else{
        
            //自定义键盘
            composeTextView.inputView = nil

            composeToolbar.isEmoticon = false
        }
    
        composeTextView.becomeFirstResponder()
        //切记刷新
        composeTextView.reloadInputViews()
    }

}
extension ZDDComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        composeTextView.backgroundColor = UIColor(patternImage: image)
        
        
        //填充图片
//        let data = UIImagePNGRepresentation(scaleImageOfWidth(600, image: image))
        
        
        pictureView.addImages(scaleImageOfWidth(600, image: image))
        picker.dismissViewControllerAnimated(false, completion: nil)
        
    }


    func scaleImageOfWidth(width:CGFloat ,image: UIImage)->UIImage{
    
        if width > image.size.width{
        
            return image
        }
    //等比算出图片的高
        let height = (width * image.size.height) / image.size.width
        //创建一个rect
        let rect = CGRect(x: 0, y: 0, width: width, height: height)
        
        //开启图形上下文
        UIGraphicsBeginImageContext(rect.size)
        //渲染到上下文
        image.drawInRect(rect)
        //获取上下文结果
        let result = UIGraphicsGetImageFromCurrentImageContext()
        //关闭图形上下文
        UIGraphicsEndImageContext()
        return result
        
    
    
    }

}














